package com.woniuxy.joylifeshop.controller;


import com.woniuxy.common.entity.ShopChat;
import com.woniuxy.common.entity.ShopChatlist;
import com.woniuxy.common.utils.JWTUtils;
import com.woniuxy.joylifeshop.service.ChatListService;
import com.woniuxy.joylifeshop.service.ChatService;
import com.woniuxy.joylifeshop.vo.ResponseInformation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class ChatController {

    @Autowired
    ChatService chatService;

    @Autowired
    ChatListService chatListService;


    /**
    * @Author SooYoo
    * @Description 初始化聊天
    * @Param
    * @Return
    **/
    @RequestMapping("/initChat")
    public ResponseInformation initChat(HttpServletRequest request,String merchantId){
        String userId = JWTUtils.getUserId(request.getHeader("token"));
        ResponseInformation responseInformation = new ResponseInformation();

        try {
            List<ShopChat> shopChats = chatService.readChatContentByUserIdAndMerchantId(userId, merchantId);
            responseInformation.setData(shopChats);
            responseInformation.setMsg("成功");

            return responseInformation;
        } catch (Exception e) {
            e.printStackTrace();
            responseInformation.setMsg("失败");

            return responseInformation;
        }
    }

    /**
    * @Author SooYoo
    * @Description 聊天吧
    * @Param
    * @Return
    **/
    @RequestMapping("/letsTalk")
    public ResponseInformation letsTalk( HttpServletRequest request,String merchantId,String essay){
        String userId = JWTUtils.getUserId(request.getHeader("token"));
        ResponseInformation responseInformation = new ResponseInformation();
        //System.out.println(essay);

        //验证消息空值
        if (essay.equals("") || essay==null){
            List<ShopChat> shopChats = chatService.readChatContentByUserIdAndMerchantId(userId, merchantId);
            responseInformation.setData(shopChats);
            responseInformation.setState(201);
            responseInformation.setMsg("发送消息不能为空");
            return responseInformation;
        }
        //找到新聊天内容的归属
        ShopChatlist shopChatlist = chatListService.ReadChatListByUserIdAndMerchantId(userId, merchantId);
        //添加新的聊天内容内容
        chatService.addessay(userId,merchantId,essay,shopChatlist.getListId());


        try {
            List<ShopChat> shopChats = chatService.readChatContentByUserIdAndMerchantId(userId, merchantId);
            responseInformation.setData(shopChats);
            responseInformation.setMsg("成功");

            return responseInformation;
        } catch (Exception e) {
            e.printStackTrace();
            responseInformation.setMsg("失败");

            return responseInformation;
        }
    }





}
